package cmd

import (
	"log"
	"os"
	"os/signal"
	"syscall"

	"gitee.com/huoyu123hk/cloudAgent/pkg/client"
	"gitee.com/huoyu123hk/cloudAgent/pkg/logx"
	"github.com/spf13/cobra"
)

var (
	agentId string
	cmd     string
)

var agentCmd = &cobra.Command{
	Use:   "agent",
	Short: "Cloud Agent",
	Long:  `Cloud Agent is a powerful agent that provides various services including task management, file transfer, tunneling, and SSH connectivity.`,
	Run: func(cmd *cobra.Command, args []string) {
		command := cmd.Flag("cmd").Value.String()
		switch command {
		case "run":
			runAgent()
		case "install":
			logx.Info("Installing Cloud Agent...")
		case "uninstall":
			logx.Info("Uninstalling Cloud Agent...")
		case "start":
			logx.Info("Starting Cloud Agent...")
		case "stop":
			logx.Info("Stopping Cloud Agent...")
		default:
			logx.Error("Invalid command specified")
			return
		}

	},
}

func init() {
	rootCmd.AddCommand(agentCmd)

	agentCmd.Flags().StringVarP(&agentId, "agentID", "i", "agent-1", "Agent ID")
	//添加命令选择 install uninstall start stop
	agentCmd.Flags().StringVarP(&cmd, "cmd", "c", "run", "Command to execute (run, install, uninstall, start, stop)")

}

func runAgent() {

	// 设置信号处理
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// 启动客户端（使用新的Run方法）
	go func() {
		logx.Info("Starting Cloud Agent...")
		app := client.NewApp(client.AgentConfig{
			ServerURL:         serverAddr,
			AuthToken:         token,
			AgentID:           agentId,
			KeepAliveInterval: 30,
		})
		if err := app.Run(); err != nil {
			log.Fatalf("Agent client failed: %v", err)
		}
	}()

	// 等待信号
	<-sigChan

	logx.Info("Shutting down Cloud Agent...")

	logx.Info("Cloud Agent stopped")
}
